﻿using System;
using System.Globalization;
using CustomerContactSystem.Core.Infrastructure.Domain;
using CustomerContactSystem.Core.Infrastructure.Utility;
using CustomerContactSystem.Core.Model;

namespace CustomerContactSystem.WebForms.Enquiries
{
    public partial class Close : BasePage {
        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id")) {
                return;
            }

            EnquiryIdCaption.Text = Request.QueryString["id"];
            EnquiryIdCaption.NavigateUrl = "~/Enquiries/View.aspx?id=" + Request.QueryString["id"];
            GetUsers();
        }

        private void GetUsers() {
            var users = UserRepository.QueryOver().OrderBy(u => u.DisplayName).Asc.List();
            BindDropDownList(MonitoredBy, users, "DisplayName", "Id", "--Select User--", "");
            BindDropDownList(AssignedTo, users, "DisplayName", "Id", "--Select User--", "");
            MonitoredBy.SelectedIndex =
                MonitoredBy.Items.IndexOf(
                    MonitoredBy.Items.FindByValue(LoggedUser.Id.ToString(CultureInfo.InvariantCulture)));
        }

        protected void CloseEnquiryClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id")) {
                return;
            }

            EnquiryCommitmentClosure commitmentClosure = null;

            var enquiryClosure = new EnquiryClosure
                {
                    CustomerWasContacted = CustomerWasAnswered.SelectedIndex > 0,
                    CustomerWasContactedBy = CustomerWasAnswered.SelectedItem.Text,
                    DateClosed = DateTime.Now,
                    ClosedBy = LoggedUser,
                    ClosedByDepartment = LoggedUser.Department,
                    ClosedByGroup = LoggedUser.UserGroup,
                    EnquiryResponse = EnquiryResponse.Text.HtmlStripped()
                };

            if (CloseWithCommitment.Checked) {
                DateTime parsedDeadline;
                DateTime.TryParse(Deadline.Text, out parsedDeadline);
                commitmentClosure = new EnquiryCommitmentClosure
                    {
                        AssignedTo = UserRepository.LoadReference(int.Parse(AssignedTo.SelectedItem.Value)),
                        Completed = false,
                        Deadline = parsedDeadline,
                        MonitoredBy = UserRepository.LoadReference(int.Parse(MonitoredBy.SelectedItem.Value))
                    };
            }

            if (!IsValidClosure(enquiryClosure, commitmentClosure)) {
                return;
            }

            var enquiryId = int.Parse(Request.QueryString["id"]);
            var enquiry = EnquiryRepository.GetById(enquiryId);

            if (commitmentClosure != null) {
                EnquiryCommitmentClosureRepository.Add(commitmentClosure);
                enquiry.AddCommitment(LoggedUser.DisplayName,commitmentClosure, enquiryClosure.DateClosed.AddMinutes(-1));
            }

            enquiryClosure.DeadlineMet = enquiryClosure.DateClosed < enquiry.Deadline;
            EnquiryClosureRepository.Add(enquiryClosure);
            enquiry.Close(LoggedUser.DisplayName, enquiryClosure, commitmentClosure == null);
            
            EnquiryRepository.Update(enquiry);
            Response.Redirect("~/Enquiries/View.aspx?id=" + enquiry.Id);
        }

        private bool IsValidClosure(Entity closure, Entity commitmentClosure) {
            if (IsValidObject(closure, CloseEnquiryResultMessage)) {
                return commitmentClosure == null || IsValidObject(commitmentClosure, CloseEnquiryResultMessage);
            }
            return false;
        }
    }
}